import { TimerManager } from "./TimerManager"

export enum TimerStatus {
    Init,
    Working,
    Pause,
    Finish,
}

export class Timer {
    private _event: Function 
    private _elapsedTime: number 
    private _lastElapsedTime: number
    private _loop: boolean 
    private _interval: number
    private _status:TimerStatus 
    private _index:number

    get index(): number {
        return this._index
    }
    get interval(): number {
        return this._interval
    }
    get loop(): boolean {
        return this._loop
    }
    get elapsedTime(): number {
        return this._elapsedTime
    }
    get event(): Function {
        return this._event
    }
    get status(): TimerStatus {
        return this._status
    }

    private set status(status: TimerStatus) {
        this._status = status
    }

    constructor(index: number, interval: number = -1, loop: boolean = false, event: Function = null) {        
        this._index = index
        this._interval = interval
        this._loop = loop
        this._event = event
        this._status = TimerStatus.Init
    }

    Update(dt: number) {
        switch(this.status){
            case TimerStatus.Init:
                this.Init()
            break        
            case TimerStatus.Working:
                this.Work(dt)
            break
            case TimerStatus.Pause:
                this.Pause()
            break
            case TimerStatus.Finish:
                this.Finish()    
            break
            default:
                break
        }
    }

    Init(){
        this._elapsedTime = 0 
        this._lastElapsedTime = 0
        this.status = TimerStatus.Working
    }

    Work(dt:number){
        if (this.interval > 0 ) {
            this._elapsedTime += dt
            while (this.elapsedTime >= this.interval) {
                this._elapsedTime -= this.interval
                this?.event(this.interval)    
                if (!this.loop) {
                    this.status = TimerStatus.Finish
                    break
                }
            }
        }
    }

    Pause() {
        //啥也不干
    }

    Finish(){
        TimerManager.GetInstance().DestroyTimer(this.index)
    }
}